﻿using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.IO;


namespace sunsetmp
{
    /// <summary>
    /// Логика взаимодействия для Settings.xaml
    /// </summary>
    public partial class Settings : Window
    {
        Core core;
        public Settings(Core c)
        {
            core = c;
            InitializeComponent();
            LoadSettings();
        }

        #region События кнопок

        private void SettingsButtons_Click(object sender, RoutedEventArgs e)
        {
            System.Windows.Controls.Button but = (System.Windows.Controls.Button)sender;
            ShowSettingsGrid(but.Name);
        }

        private void OkButton_Click(object sender, RoutedEventArgs e)
        {
            ApplySettings();
            this.Close();
        }

        private void Border_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            this.DragMove();
        }

        private void Window_StateChanged(object sender, EventArgs e)
        {
            if (this.WindowState == System.Windows.WindowState.Maximized)
                this.WindowState = System.Windows.WindowState.Normal;
        }

        private void CloseW_Click(object sender, RoutedEventArgs e)
        {
            LoadColor();
            this.Close();
        }

        private void ApplyButton_Click(object sender, RoutedEventArgs e)
        {
            ApplySettings();
        }

        private void FolderDialogButton_Click(object sender, RoutedEventArgs e)
        {
            System.Windows.Forms.FolderBrowserDialog dialog = new System.Windows.Forms.FolderBrowserDialog();
            if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                DownloadPathBox.Text = dialog.SelectedPath;
        }


        #endregion

        private void LoadSettings()
        {
            string currentDir = Path.GetDirectoryName(System.Windows.Forms.Application.ExecutablePath);
            Properties.Settings set = Properties.Settings.Default;
            DownloadPathBox.Text = set.downDir;
            LoadHotKeyButtons();
            string[] themes = Directory.GetFiles(currentDir + "\\Themes", "*.xaml");
            for (int i = 0; i < themes.Length; i++)
                themes[i] = Path.GetFileNameWithoutExtension(themes[i]);
            ThemeComboBox.ItemsSource = themes;
            ThemeComboBox.SelectedItem = set.ThemeName;
            OpenTitleInMinimal.IsChecked = set.ShowTitleInMinimal;
            OpenSliderAtStart.IsChecked = set.ShowMenuInStart;
            CheckUpdateFlag.IsChecked = !set.DontCheckUpdate;
            LoadColor();
        }

        public Dictionary<string, string> ConvertStringToDic(string str)
        {
            if (str == null || str == "")
                return null;
            Dictionary<string, string> dic = new Dictionary<string, string>();
            string[] spit = str.Split('№');
            foreach (string s in spit)
                if (s != "")
                    dic.Add(s.Split('~')[0], s.Split('~')[1]);
            return dic;
        }

        private string ConvertDicToString(Dictionary<string, string> dic)
        {
            if (dic == null)
                return null;
            string res = "";
            foreach (string key in dic.Keys)
                res += key + "~" + dic[key] + "№";
            return res;
        }

        private void LoadColor()
        {
            Properties.Settings set = Properties.Settings.Default;
            BrushConverter conv = new BrushConverter();
            Brush brush;
            if (set.BkgColor != "")
            {
                brush = conv.ConvertFromString(set.BkgColor) as Brush;
                BackgroundColorBox.Text = brush.ToString();
                Application.Current.Resources.Remove("MyBackground");
                Application.Current.Resources.Add("MyBackground", brush);
            }
            if (set.TextColor != "")
            {
                brush = conv.ConvertFromString(set.TextColor) as Brush;
                TextColorBox.Text = brush.ToString();
                Application.Current.Resources.Remove("MyTextColor");
                Application.Current.Resources.Add("MyTextColor", brush);
            }
            if (set.IconColor != "")
            {
                brush = conv.ConvertFromString(set.IconColor) as Brush;
                IconColorBox.Text = brush.ToString();
                Application.Current.Resources.Remove("MyItemColor");
                Application.Current.Resources.Add("MyItemColor", brush);
            }
            if (set.VkIconColor != "")
            {
                brush = conv.ConvertFromString(set.VkIconColor) as Brush;
                VkIconColorBox.Text = brush.ToString();
                Application.Current.Resources.Remove("MyVkItemColor");
                Application.Current.Resources.Add("MyVkItemColor", brush);
            }
        }

        private void LoadHotKeyButtons()
        {
            Properties.Settings set = Properties.Settings.Default;
            Dictionary<string,string> dic = ConvertStringToDic(set.HotKeys);
            string[] names = { "Воспроизвести/Приостановить", "Следующий трек", "Предыдущий трек", "Стоп", "Проигрывать вперемешку", "Повторять текущий трек", "Скачать текущий трек", "Добавить в мои аудиозаписи", "Показать/скрыть в трей", "Поверх всех окон", "Громче", "Тише", "Выключить звук", "Перемотать назад", "Перемотать вперед" };
            if (dic == null || dic.Count != names.Length)
            {
                dic = new Dictionary<string, string>();
                foreach (string n in names)
                    dic.Add(n, "");
                set.HotKeys = ConvertDicToString(dic);
                set.Save();
            }
            GridLengthConverter converter = new GridLengthConverter();
            int i = 0;
            foreach (string key in dic.Keys)
            {
                var rowDefinition = new RowDefinition();
                var rowDefinitionSplit = new RowDefinition();
                rowDefinition.Height = (GridLength)converter.ConvertFromString("26");
                rowDefinitionSplit.Height = (GridLength)converter.ConvertFromString("4");
                HotKeySettingsGrid.RowDefinitions.Add(rowDefinition);
                HotKeySettingsGrid.RowDefinitions.Add(rowDefinitionSplit);
                /////
                Grid grid = new Grid();
                grid.Height = 1.45;
                grid.Background = Brushes.Black;
                Grid.SetColumnSpan(grid, 5);
                Grid.SetRow(grid, (i*2)+1);
                HotKeySettingsGrid.Children.Add(grid);
                /////
                Label label = new Label();
                label.Foreground = (Brush) FindResource("MyTextColor");
                label.Content = key;
                Grid.SetRow(label, i*2);
                HotKeySettingsGrid.Children.Add(label);
                /////
                TextBox tBox = new TextBox();
                tBox.IsReadOnly = true;
                tBox.PreviewKeyDown += tBox_KeyDown;
                tBox.CommandBindings.Clear();
                tBox.Height = 26;
                tBox.Text = dic[key].ToString();
                Grid.SetRow(tBox, i *2);
                Grid.SetColumn(tBox, 2);
                HotKeySettingsGrid.Children.Add(tBox);
                i++;
            }
        }

        private void SaveHotKeys(Properties.Settings settings)
        {
            Dictionary<string, string> dic = ConvertStringToDic(settings.HotKeys);
            if (dic == null)
                return;
            for (int i=3;i<= HotKeySettingsGrid.Children.Count;i+=3)
            {
                Label label = HotKeySettingsGrid.Children[i - 2] as Label;
                TextBox tBox = HotKeySettingsGrid.Children[i - 1] as TextBox;
                dic[label.Content.ToString()] = tBox.Text;
                if (tBox.Text != "")
                    core.RegisterHotKey(label.Content.ToString(), tBox.Text);
            }
            settings.HotKeys = ConvertDicToString(dic);
        }

        void tBox_KeyDown(object sender, KeyEventArgs e)
        {
            TextBox tBox = (TextBox)sender;
            if (e.Key == Key.Escape || e.Key == Key.Back)
            {
                tBox.Text = "";
                return;
            }
            if (tBox.Text != "")
                if (tBox.Text[tBox.Text.Length -1] != ' ')
                    tBox.Text = "";
            if ((e.SystemKey == Key.LeftAlt || e.SystemKey == Key.RightAlt) && tBox.Text.IndexOf("Alt") == -1)
                tBox.Text += "Alt + ";
            if ((e.Key == Key.LWin || e.Key == Key.RWin) && tBox.Text.IndexOf("Win") == -1)
                tBox.Text += "Win + ";
            if ((e.Key == Key.RightShift || e.Key == Key.LeftShift) && tBox.Text.IndexOf("Shift") == -1)
                tBox.Text += "Shift + ";
            if ((e.Key == Key.LeftCtrl || e.Key == Key.RightCtrl) && tBox.Text.IndexOf("Ctrl") == -1)
                tBox.Text += "Ctrl + ";
            if (isNotModifKey(e.Key))
                tBox.Text += e.Key.ToString();
            else
                if (isNotModifKey(e.SystemKey) && tBox.Text.IndexOf("Alt") != -1)
                    tBox.Text += e.SystemKey.ToString();
        }

        private bool isNotModifKey(Key key)
        {
            Key[] keys = { Key.LWin, Key.RWin, Key.LeftAlt, Key.LeftCtrl, Key.LeftShift, Key.RightAlt, Key.RightCtrl, Key.RightShift, Key.System };
            foreach (Key k in keys)
                if (k == key)
                    return false;
            return true;
        }

        private void ApplySettings()
        {
            Properties.Settings set = Properties.Settings.Default;
            set.downDir = DownloadPathBox.Text;
            SaveHotKeys(set);
            set.IconColor = IconColorBox.Text;
            set.TextColor = TextColorBox.Text;
            set.ThemeName = ThemeComboBox.SelectedValue.ToString();
            set.BkgColor = BackgroundColorBox.Text;
            set.VkIconColor = VkIconColorBox.Text;
            set.ShowMenuInStart = OpenSliderAtStart.IsChecked.Value;
            set.ShowTitleInMinimal = OpenTitleInMinimal.IsChecked.Value;
            set.DontCheckUpdate = !CheckUpdateFlag.IsChecked.Value;
            set.Save();
            LoadColor();
        }

        private void ShowSettingsGrid(string buttonName)
        {
            string gridName = buttonName.Replace("Button", "Grid");
            Grid[] grids = { GrandSettingsGrid, HotKeySettingsGrid, ThemeSettingsGrid };
            foreach (Grid g in grids)
            {
                if (g.Name == gridName)
                    g.Visibility = System.Windows.Visibility.Visible;
                else
                    if (g.Visibility == System.Windows.Visibility.Visible)
                        g.Visibility = System.Windows.Visibility.Hidden;
            }
        }

        private void ThemeComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            string currentDir = Path.GetDirectoryName(System.Windows.Forms.Application.ExecutablePath);
            if (e.AddedItems.Count != 0)
            {
                string[] split = Application.Current.Resources.MergedDictionaries[0].Source.ToString().Split('/');
                if (e.AddedItems[0] + ".xaml" != split[split.Length - 1])
                {
                    string path = currentDir + "\\Themes\\" + e.AddedItems[0] + ".xaml";
                    System.Xml.XmlReader xmlReader = System.Xml.XmlReader.Create(path);
                    ResourceDictionary resource = (ResourceDictionary)System.Windows.Markup.XamlReader.Load(xmlReader);
                    resource.Source = new Uri(path);
                    Application.Current.Resources.MergedDictionaries[0] = resource;
                }
            }
        }

        private System.Drawing.Color GetColorFromTextBox(string buttonName)
        {
            string value = "";
            switch (buttonName)
            {
                case "BackgroundColorButton":
                    value = BackgroundColorBox.Text;
                    break;
                case "TextColorButton":
                    value = TextColorBox.Text;
                    break;
                case "IconColorButton":
                    value = IconColorBox.Text;
                    break;
                case "VkIconColorButton":
                    value = VkIconColorBox.Text;
                    break;
            }
            if (value != "")
                return System.Drawing.ColorTranslator.FromHtml(value);
            else
                return System.Drawing.Color.Black;
        }

        private void ColorButton_Click(object sender, RoutedEventArgs e)
        {
            Button but = (Button)sender;
            System.Windows.Forms.ColorDialog colorDialog = new System.Windows.Forms.ColorDialog();
            colorDialog.Color = GetColorFromTextBox(but.Name);
            if (colorDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                Brush brush = new SolidColorBrush(Color.FromArgb(colorDialog.Color.A, colorDialog.Color.R, colorDialog.Color.G, colorDialog.Color.B));
                switch (but.Name)
                {
                    case "BackgroundColorButton":
                        BackgroundColorBox.Text = brush.ToString();
                        Application.Current.Resources.Remove("MyBackground");
                        Application.Current.Resources.Add("MyBackground", brush);

                        break;
                    case "TextColorButton":
                        TextColorBox.Text = brush.ToString();
                        Application.Current.Resources.Remove("MyTextColor");
                        Application.Current.Resources.Add("MyTextColor", brush);
                        break;
                    case "IconColorButton":
                        IconColorBox.Text = brush.ToString();
                        Application.Current.Resources.Remove("MyItemColor");
                        Application.Current.Resources.Add("MyItemColor", brush);
                        break;
                    case "VkIconColorButton":
                        VkIconColorBox.Text = brush.ToString();
                        Application.Current.Resources.Remove("MyVkItemColor");
                        Application.Current.Resources.Add("MyVkItemColor", brush);
                        break;

                }
            }
        }
        
    }
}
